package com.minshenglife.zanzan.web.weixin;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.minshenglife.zanzan.entity.OperateLog;
import com.minshenglife.zanzan.entity.RedFlower;
import com.minshenglife.zanzan.entity.Review;
import com.minshenglife.zanzan.entity.TurntableResult;
import com.minshenglife.zanzan.entity.User;
import com.minshenglife.zanzan.pub.Keys;
import com.minshenglife.zanzan.pub.utils.Message;
import com.minshenglife.zanzan.result.GameHallResult;
import com.minshenglife.zanzan.service.OperateLogService;
import com.minshenglife.zanzan.service.RedFlowerService;
import com.minshenglife.zanzan.service.ReviewService;
import com.minshenglife.zanzan.service.TurntableResultService;
import com.minshenglife.zanzan.service.UserService;
import com.minshenglife.zanzan.web.weixin.cst.GamePrompts;
import com.nationsky.pub.utils.StringUtils;


/**
 * 幸运转盘
 * @author huodd
 * 
 */
@Controller
@RequestMapping("/gameHall")
public class GameHallController extends BaseController{
	Logger log = LoggerFactory.getLogger(GameHallController.class);
	@Resource
	TurntableResultService resultService;
	@Resource
	RedFlowerService redFlowerService;
	@Resource
	UserService userService;
	@Resource
	ReviewService reviewService;
	@Resource
	OperateLogService logService;
    
    /**
     * 开始抽奖
     * @param request
     * @param response
     * @param bindForm
     * @return
     */
    @RequestMapping(value="gameStart.do",method=RequestMethod.POST)
    @ResponseBody
    public Message gameStart(HttpServletRequest request, HttpServletResponse response){
    	Message message=null;
    	OperateLog opLog=null;
    	TurntableResult result=null;
    	String con="";
    	String str="";
    	String userId=null;
    	try {
    		String operator=super.getEmpId(request);
    		String openId=super.getOpenId(request);
			log.debug("当前操作人："+operator);
    		String empId=operator;
    		//校验是否已经送出两朵红花(是否有抽奖资格：1、是否已经送出两朵2、是否已经抽奖)
    		message=isStartGame(empId);
    		if(Message.STATE_200.equals(message.getState())){
//    			String sta=request.getParameter("gameSta");
//        		if("0".equals(sta)){//开始
//        			
//        		}else if("1".equals(sta)){//结束
        			
        			if(StringUtils.isNullOrEmpty(empId)){
        				message=new Message(Message.STATE_one,"empId不能为空");
        				return message;
        			}
        			User user=userService.getUserInfo(empId);
        			userId=user.getEmpId();
        			
        			int[] data = new int[]{1,0,1,0,2,0,2,0,3,0,3,0}; 
					int val = data[(int) Math.floor(Math.random()*data.length)];
					log.debug("=====抽奖结果："+val);
					int num=0;//奖品数量
					String cuccessMsg="";
					if(Keys.TURNTABLERESULT_STATE_THREE.equals(String.valueOf(val))){//积分获得数据量
						int[] arr = new int[]{8,18,28,38,48,58,68,78,88,98}; //积分数组
						num = arr[(int) Math.floor(Math.random()*arr.length)];
						log.debug("=====抽到积分数："+num);
						//更新用户信息
						userService.updateUserIntegralNumOfLuckDraw(openId,num);
						
						str="获得"+num+"积分";
						cuccessMsg="人品大爆发耶！ <br/>恭喜亲获得"+num+"个积分，升官近在咫尺啦！";
					}else if(Keys.TURNTABLERESULT_STATE_ONE.equals(String.valueOf(val))){//红花获得数据量
						num=1;
						//更新用户信息
						userService.updateUserCanSendFlowerNumOfLuckDraw(openId,num);
						
						str="获得一次赠送他人红花的机会";
						cuccessMsg="恭喜亲！<br/>获得红花赠送机会 1 次，快把这多红花赠送给心目中的TA吧！";
					}else if(Keys.TURNTABLERESULT_STATE_TWO.equals(String.valueOf(val))){//吐槽机会
						num=1;
						//更新用户吐槽机会信息
//						user.setCanTuCaoNum(user.getCanTuCaoNum()+1);
//						userService.updateUserInfo(user);
						userService.updateUserCanTuCaoNumOfLuckDraw(openId, num);
						str="获得一次吐槽机会";
						cuccessMsg="手气真不错！<br/>恭喜亲获得吐槽机会 1 次，快把你的小心思一吐为快吧！";
					}else{
						str="什么都没有得到";
						cuccessMsg="不要灰心哦！<br/>意外惊喜总会不期而至，期待明天吧！";
						result=new TurntableResult(Keys.TURNTABLERESULT_STATE_FOUR,userId,0,0);
						//添加转盘结果表数据
						resultService.add(result);
					}
					//添加一条新鲜事
					Review review=new Review();
					review.setCriticsId(user.getEmpId());
					review.setByCriticsId(Keys.SYSTEM_SUPER_USER);//没有被评论对象，用系统管理员代替
					review.setReviewContent(user.getEmp_name()+"在幸运大转盘中"+str);
					review.setCriticsType(Keys.REVIEW_CRITICS_TYPE_ZERO);
					review.setReviewType(Keys.REVIEW_TYPE_FOUR);
					reviewService.add(review);
					
					con="["+user.getEmpId()+"|"+user.getEmp_name()+"]在幸运大转盘中"+str;
					log.debug(con);
					opLog=new OperateLog(user.getEmpId(),Keys.OPERATE_LOG_TYPE_EIGHT,Keys.OPERATE_LOG_STATE_SUCCESS,con);
					
					message=new Message(Message.STATE_200,cuccessMsg,new GameHallResult(String.valueOf(val),String.valueOf(num))) ;
        		}else{
        			opLog=new OperateLog(empId,Keys.OPERATE_LOG_TYPE_EIGHT,Keys.OPERATE_LOG_STATE_EXCEPTION,message.getMsg());
        		}
//    		}
    		
		} catch (Exception e) {
			e.printStackTrace();
			userId=userId==null? Keys.SYSTEM_SUPER_USER : userId;
			opLog=new OperateLog(userId,Keys.OPERATE_LOG_TYPE_EIGHT,Keys.OPERATE_LOG_STATE_EXCEPTION,"服务器异常");
			message=new Message(Message.STATE_one,"服务器异常");
			log.debug("服务器异常");
		}finally{
	    	//插入操作日志信息
	    	logService.add(opLog);
		}
        return message;
    }
    /**
     * 校验是否已经送出两朵红花(是否有抽奖资格：1、是否已经送出两朵2、是否已经抽奖)
     * @return
     */
	private Message isStartGame(String empId) {
		//是否已经送出两朵 红花流水中查询
		List<RedFlower> list=redFlowerService.findMyRedFlowerList(empId,new Date(),new Date(),false);
		if(list==null || list.size()<2){
			return new Message(Message.STATE_one,GamePrompts.COMMENT_NUMBER_NOT_ENOUGH);
		}else{
			//今天已经送出两朵
			if(list.size()>=2){
				//是否已经抽奖 幸运抽奖结果表中查询
				List<TurntableResult> list2=resultService.findLuckResultList(empId,new Date(),new Date());
				if(list2!=null && list2.size() > 0 ){
					return new Message(Message.STATE_one,GamePrompts.GAME_PLAYED);
				}
			}
		}
		return new Message(Message.STATE_200);
	}

	public static void main(String[] sdf){
		System.out.println("sadfd".substring(0, 1));
		
		int[] data = new int[]{1,4,4,2,4,4,3,4,4}; //返回的数组
		for(int i=0;i<10;i++){
		int val = data[(int) Math.floor(Math.random()*data.length)];
		System.out.println(val);
		
		System.out.println(Keys.TURNTABLERESULT_STATE_THREE.equals(String.valueOf(3)));
		
		}
	}
   
}
